<?php

//用户淘宝帐号信息
class MembersTaobaoModel extends BaseModel {

    public function tableName() {
        return '{{members_taobao}}';
    }

    public function rules() {
        return array(
            array('uid', 'unique', 'allowEmpty' => false, 'message' => '该用户名已经绑定过旺旺！'),
            array('taobao_user_nick', 'required', 'message' => '旺旺号不能为空！'),
            array('modify, add_time, update_time', 'safe'),
        );
    }

    public function attributeLabels() {
        return array(
            'uid' => 'member_id',
            'taobao_user_nick' => '旺旺号',
            'modify' => '是否有修改',
            'add_time' => 'Add Time',
            'update_time' => 'Update Time',
        );
    }

    //数据保存前置操作
    protected function beforeSave() {
        if ($this->isNewRecord) {
            $this->modify = 0;
            $this->update_time = $this->add_time = time();
        }
        return true;
    }

    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public function getMemberTB($uid) {
        $uid = (int) $uid;
        if (!$uid) {
            return false;
        }
        $memberTB = $this->find("uid = :uid", array(':uid' => $uid));
        return $memberTB;
    }

    /**
     *  绑定/更新旺旺
     * @param type $uid
     * @param type $wangwang
     * @return boolean
     */
    public function saveWangwang($uid, $wangwang) {
        if (empty($uid)) {
            return false;
        }
        $data = $this->find($this->where(array('uid' => $uid)));
        if (empty($data)) {
            $this->attributes = array(
                'uid' => $uid,
                'taobao_user_nick' => $wangwang,
            );
            $this->setIsNewRecord(true);
            if ($this->validate() && $this->save()) {
                return true;
            }
        } else {
            $data->taobao_user_nick = $wangwang;
            $data->update_time = time();
            $data->modify = 1;
            if ($this->validate() && $this->save()) {
                return true;
            }
        }
        return false;
    }

    /**
     * 是否绑定旺旺
     * @param type $uid 用户UID
     * @return boolean true绑定
     */
    public function isBinding($uid) {
        if (empty($uid)) {
            return false;
        }
        $info = $this->find($this->where(array('uid' => $uid)));
        if (!empty($info)) {
            return true;
        }
        return false;
    }

    /**
     * 解除旺旺绑定
     * @param type $uid 用户UID
     * @return boolean
     */
    public function relieve($uid) {
        if (empty($uid)) {
            return false;
        }
        return $this->deleteAll($this->where(array('uid' => $uid)));
    }

}
